package com.frxuexi.mymvi

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import kotlinx.coroutines.launch

/**
 * mvi流程：
 * 1.页面发送意图Intent
 * 2.ViewModel接收意图并处理意图
 * 3.请求网络-结果放入State
 * 4.页面监听到State的变化，更新UI
 */
@Composable
fun NewsPage(vm:NewsViewModel= hiltViewModel()) {
    //带状态的集合
    var list = remember {
        SnapshotStateList<RecordData>()
    }


    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is NewsState.onSuccess->{
                        Log.i("===",it.data.toString())
                        list.addAll(it.data)
                    }
                    is NewsState.onError->{
                        Log.i("===",it.msg)
                    }
                    else->{}
                }
            }
        }

        launch {
//            1.页面发送意图Intent
            vm.channel.send(NewsIntent.getNews(1))
        }
    })

    LazyColumn(Modifier.padding(10.dp),verticalArrangement = Arrangement.spacedBy(10.dp), content = {
        items(list){
            AsyncImage(model = it.imgurl, contentDescription = "", modifier = Modifier.fillMaxWidth(),contentScale= ContentScale.Crop)
            Spacer(modifier = Modifier.height(5.dp))
            Text(text = it.title)
        }
    })
}